#include <iostream>
#include <thread>
#include <mutex>

std::recursive_mutex rec_mtx;  // 全局递归互斥量
int shared_data = 0;  // 共享数据

void recursive_increment(int id, int level) {
    if (level == 0) {
        return;  // 递归结束条件
    }

    std::lock_guard<std::recursive_mutex> lock(rec_mtx);  // 自动获取互斥量的锁
    ++shared_data;  // 修改共享数据
    std::cout << "Thread " << id << " increased shared data to " << shared_data << " at level " << level << std::endl;

    recursive_increment(id, level - 1);  // 递归调用，再次尝试获取锁
    // 锁在 lock_guard 对象析构时自动释放
}

int main() {
    std::thread t1(recursive_increment, 1, 3);  // 线程1递归三层
    std::thread t2(recursive_increment, 2, 3);  // 线程2递归三层

    t1.join();
    t2.join();

    std::cout << "Final value of shared data: " << shared_data << std::endl;

    return 0;
}